﻿using Cxuu.Common;
using Cxuu.Models;
using PetaPoco;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [AppService]
    public class ArticleMarkRepository : BaseRepository<ArticleMark, PetaPocoContext>
    {

        public ArticleMarkRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        public async Task<ViewArticleMark> GetOneAsync(int aid)
        {
            Sql sql = Sql.Builder;
            sql.Select("userArt.Nickname,user.Nickname as MarkName,article.Title,article.InsertTime,mark.*")
                 .From("cxuu_article_mark as mark")
                 .LeftJoin("cxuu_admin_user as user").On("mark.Uid=user.Id");
            sql.LeftJoin("cxuu_article as article").On("article.Id=mark.Aid");
            sql.LeftJoin("cxuu_admin_user as userArt").On("userArt.Id=article.Uid");
            sql.Where("mark.Aid =@0", aid);
            return await CreateDAO().FirstOrDefaultAsync<ViewArticleMark>(sql);
        }

        public async Task<int> InsertOrUpdateAsync(ArticleMark editArticleMark)
        {
            int res;
            //return await CreateDAO().SaveAsync(editArticleMark,);
            if (CreateDAO().IsNew(editArticleMark))
            {
                var obj = await CreateDAO().InsertAsync(editArticleMark);
                res = obj.ParseToInt();
            }
            else
            {
                res = await CreateDAO().UpdateAsync(editArticleMark);
            }
            return res;
        }
    }
}
